package ar.edu.caece.compiler.grammar.factories;

import ar.edu.caece.compiler.grammar.AbstractTokenVisitorFactory;
import ar.edu.caece.compiler.grammar.GrammarSymbol;
import ar.edu.caece.compiler.grammar.TokenVisitorInterface;
import ar.edu.caece.compiler.grammar.nonterminals.EXPR2;
import ar.edu.caece.compiler.grammar.nonterminals.EXPR2A;
import ar.edu.caece.compiler.grammar.nonterminals.EXPR3;
import ar.edu.caece.compiler.grammar.terminals.GrammarTerminal;

public class EXPR2Factory extends AbstractTokenVisitorFactory {

	private static EXPR2Factory INSTANCE;
	
	public static EXPR2Factory getInstance() throws Exception {
		if(INSTANCE==null) INSTANCE = new EXPR2Factory();
		return INSTANCE;
	}
	
	private EXPR3Factory expr3Factory;
	private EXPR2AFactory expr2aFactory;
	private TokenVisitorInterface parseEXPR3;
	private TokenVisitorInterface parseEXPR2A;
	
	private Initializer initializer = new Initializer() {
		
		@Override
		public void init() throws Exception {
			initializer = NoOperationInitializer.getInstance();
			expr3Factory = EXPR3Factory.getInstance();
			expr2aFactory = EXPR2AFactory.getInstance();
			parseEXPR2A = expr2aFactory.makeVisitor();
			parseEXPR3 = expr3Factory.makeVisitor();
		}
	};
	
	private EXPR2Factory() throws Exception {

	}
	
	@Override
	public TokenVisitorInterface makeChainedVisitor(
			final TokenVisitorInterface siguiente) throws Exception {
		initializer.init();

		return new TokenVisitorInterface() {

			@Override
			public GrammarSymbol defaultCase(GrammarTerminal llamador)
					throws Exception {
				GrammarSymbol result = llamador.execute(expr3Factory.makeChainedVisitor(siguiente));
				if(result instanceof EXPR3) {
					return new EXPR2 ((EXPR3) result, (EXPR2A) nextToken().execute(parseEXPR2A)); 
				} 
				else {
					return result;
				}
			}
			
		};
	
	}
	@Override
	public TokenVisitorInterface makeVisitor() throws Exception {
		initializer.init();

		return new TokenVisitorInterface() {

			@Override
			public GrammarSymbol defaultCase(GrammarTerminal llamador) throws Exception {
				return new EXPR2 ((EXPR3) llamador.execute(parseEXPR3), (EXPR2A) nextToken().execute(parseEXPR2A));
			}
		};
	}
	
	
}
